// utils/netSpeed.js

let lastRx = 0 // 上次接收字节数
let lastTx = 0 // 上次发送字节数
let lastTime = 0
let timer = null

const NetSpeed = {
  /**
   * 开始监控网速
   * @param {Function} callback 回调函数，返回 { downloadSpeed, uploadSpeed } 单位 KB/s
   * @param {Number} interval 间隔时间，毫秒
   */
  start(callback, interval = 2000) {
    if (timer) return

    lastTime = Date.now()

    timer = setInterval(() => {
      try {
        // 获取总流量字节数 (App-Plus 原生 API)
        const info = plus.networkinfo.getCurrentAPN()
        // info 下可能包含 bytesReceived/bytesSent（视平台而定）

        const rx = info && info.bytesReceived || 0
        const tx = info && info.bytesSent || 0

        const now = Date.now()
        const deltaTime = (now - lastTime) / 1000 // 秒

        let downloadSpeed = 0
        let uploadSpeed = 0

        if (lastRx && lastTx) {
          downloadSpeed = ((rx - lastRx) / 1024 / deltaTime).toFixed(2) // KB/s
          uploadSpeed = ((tx - lastTx) / 1024 / deltaTime).toFixed(2)   // KB/s
        }

        lastRx = rx
        lastTx = tx
        lastTime = now

        callback && callback({
          downloadSpeed,
          uploadSpeed
        })
      } catch (e) {
        console.error("获取网速失败：", e)
      }
    }, interval)
  },

  /**
   * 停止监控
   */
  stop() {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
  }
}

export default NetSpeed
